package com.baitengsoft.patentapimonitor.api.service.impl;

import com.baitengsoft.patentapimonitor.api.dao.PacTypeDao;
import com.baitengsoft.patentapimonitor.api.entity.PacTypeEntity;
import com.baitengsoft.patentapimonitor.api.model.PacTypeViewModel;
import com.baitengsoft.patentapimonitor.api.service.PacTypeService;
import com.baitengsoft.patentapimonitor.common.utils.PageResult;
import com.baitengsoft.patentapimonitor.common.utils.Res;
import com.baitengsoft.patentapimonitor.common.utils.SearchParam;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by QEK on 2017/12/18.
 */
@Service
public class PacTypeServiceImpl extends BaseServiceImpl<PacTypeEntity> implements PacTypeService {

    @Autowired
    private PacTypeDao pacTypeDao;

    /**
     * 查询平台的权利人类型
     * @param platformId
     * @return
     */
    @Override
    public List<PacTypeViewModel> selectPacTypes(Integer platformId) {

        Mapper<PacTypeEntity> mapper = this.getMapper();
        Example example = new Example(PacTypeEntity.class);
        //查询当前平台的一级权利人类型
        example.createCriteria().andEqualTo("platformid",platformId).andEqualTo("parentid",0).andEqualTo("status",1);
        example.orderBy("sort").asc();
        List<PacTypeEntity> oneLevelList = mapper.selectByExample(example);

        List<PacTypeViewModel> resultList = new ArrayList<>();

        for(PacTypeEntity entity : oneLevelList ){
            List<String> twoLevelList = getTwoLevelsStringByParentId(entity.getId());
            PacTypeViewModel model = new PacTypeViewModel();
            if(twoLevelList != null){
                String s = twoLevelList.toString();
                model.setTwoLevelString(s.substring(1,s.length()-1));
                model.setTwoLevelList(twoLevelList);
            }
            model.setId(entity.getId());
            model.setName(entity.getName());
            resultList.add(model);
        }
        return resultList;

    }

    /**
     * 根据parentID分页查询二级分类类型
     * @param parentId
     * @return
     */
    @Override
    public PageResult<PacTypeEntity> selectTwoLevelTypeByParentId(Integer platformId,Integer parentId, SearchParam param) {
        Mapper<PacTypeEntity> mapper = this.getMapper();
        Example example = new Example(PacTypeEntity.class);
        //查询当前平台的一级权利人类型下的二级权利人类型  status=1表示正常 -1表示删除
        example.createCriteria().andEqualTo("platformid",platformId).andEqualTo("parentid",parentId).andEqualTo("status",1);
        int count = mapper.selectCountByExample(example);
        //排序
        example.orderBy("sort").asc();
        RowBounds rb = new RowBounds(param.getPageNumber(),param.getPageSize());
        List<PacTypeEntity> list = mapper.selectByExampleAndRowBounds(example,rb);
        return new PageResult<PacTypeEntity>(list,param.getPageNumber(),param.getPageSize(),count);

    }

    /**
     * 新增、修改二级权利人类型
     * @param model
     * @return
     */
    @Override
    public Res addTwoLevelType(PacTypeViewModel model,Integer userId,Integer platformId) {
        if(typeNameIsExist(model.getName(),platformId)){
            return Res.error("该权利人类型已存在！");
        }
        int result = 0;
        if(model.getId() != null && model.getId() > 0){//修改操作
            PacTypeEntity entity = queryById(model.getId());
            entity.setName(model.getName());
            result = updateByNotNull(entity);
            if(result == 1){
                return Res.ok("修改成功！");
            }
            return Res.error("修改失败！");
        }else {
            PacTypeEntity entity = new PacTypeEntity();
            entity.setStatus(1);
            entity.setUpdateoperid(userId);
            entity.setName((model.getName() == null || model.getName().isEmpty()) ? "" : model.getName().trim());
            entity.setCreatedate(new Date());
            entity.setCreateoperid(userId);
            entity.setLevels(2);
            entity.setParentid(model.getParentId());
            entity.setSort(1);
            entity.setPlatformid(platformId);
            entity.setUpdatedate(new Date());
            result = saveByNotNull(entity);
            if(result == 1){
                return Res.ok("添加成功！");
            }
            return Res.error("添加失败！");
        }

    }

    /**
     * 删除
     * @param id
     * @return
     */
    @Override
    public Res deleteTwoLevelType(Integer id) {
        PacTypeEntity entity = queryById(id);
        entity.setStatus(-1);//逻辑删除：1：正常，-1：删除
        int result = updateByNotNull(entity);
        if(result == 1){
            return Res.ok("删除成功！");
        }
        return Res.error("删除失败！");
    }

    /**
     * 根据id，查询单个二级权利人类型详情
     * @param id
     * @return
     */
    @Override
    public PacTypeEntity getTwoLevelTypeById(Integer id) {
        PacTypeEntity entity = queryById(id);
        return entity;
    }

    /**
     * 新增之前判断name是否已经存在
     * @param name
     * @return
     */
    private boolean typeNameIsExist(String name,Integer platformId) {
        Mapper<PacTypeEntity> mapper = this.getMapper();
        Example example = new Example(PacTypeEntity.class);
        example.createCriteria().andEqualTo("platformid",platformId).andEqualTo("name",name).andEqualTo("status",1);
        List<PacTypeEntity> list = mapper.selectByExample(example);
        if(list.size() > 0){
            return true;
        }
        return false;
    }

    private List<String> getTwoLevelsStringByParentId(Integer id) {
        List<String> list = pacTypeDao.getTwoLevelNameByParentID(id);
        if(list != null && list.size() > 0 ){
            return list;
        }
        return null;
    }



}
